<?php

!defined('IN_HDWIKI') && exit('Access Denied');

class searchmodel {

	var $db;
	var $base;

	function searchmodel(&$base) {
		$this->base = $base;
		$this->db = $base->db;
	}
	
	function get_total_num($sql){
		$query=$this->db->query($sql);
		$data=$this->db->fetch_array($query);
		return $data['num'];
	}
	
	function fulltext_search($sql,$start=0,$limit=10){
		$doclist=array();
		$query=$this->db->query($sql." limit $start,$limit");
		while($doc=$this->db->fetch_array($query)){
			$doc['time']=$this->base->date($doc['time']);
			$doc['tag']=$_ENV['doc']->spilttags($doc['tag']);
			$doclist[]=$doc;
		}
		return $doclist;
	}
	
	function join_sql($element){
		if(preg_match("(AND|\+|&|\s)", $element['keyword']) && !preg_match("(OR|\|)", $element['keyword'])) {
			$andor = ' AND ';
			$sqlkeywords=1;
			$keywords = preg_replace("/( AND |&| )/is", "+", $element['keyword']);
		} elseif(preg_match("(OR|\|)", $element['keyword'])) {
			$andor = ' OR ';
			$sqlkeywords=0;
			$keywords = preg_replace("/( OR |\|)/is", "+", $element['keyword']);
		}else{
			$keywords = $element['keyword'];
		}
		$keywords = str_replace('*', '%', addcslashes($keywords, '%_'));
		foreach(explode('+', $keywords) as $text) {
			$text = trim($text);
			if($text) {
				$sqlkeywords .=$andor;
				$sqlkeywords .="d.".$element['searchtype']." LIKE '%$text%'";
				}
		}
		$sqladd=(trim($sqlkeywords)!='')?' AND ('.$sqlkeywords.")":"";
		$sqladd .=(bool)$element['author']?" AND d.author like '".$element['author']."' ":"";
		$sqladd .=('all'!=$element['categoryid'][0])?' AND d.cid in ('.implode(',',$element['categoryid']).') ':'';
		if(0!=$element['timelimited']){
			$sqladd .=('within'==$element['withinbefore'])?" AND d.`time` > '".($this->base->time-$element['timelimited'])."'" :" AND d.`time` < '".($this->base->time-$element['timelimited'])."'";
		}
		$order=" ORDER BY d.".$element['ordertype']." ".$element['ascdesc']."";
		$result['sql']='SELECT d.did,d.tag,d.title,d.author,d.authorid,d.time,d.summary,d.edits, d.views,d.comments FROM '.DB_TABLEPRE.'doc d  WHERE 1 '.$sqladd.$order;
		$result['dsql']='SELECT COUNT(*) as num FROM '.DB_TABLEPRE.'doc d WHERE 1 '.$sqladd;
		return $result;
	}
}


?>